import React, { forwardRef, useEffect, useState } from 'react';
import { TreeSelect } from 'antd';

import { querySalaryItemsTree } from '@/services/salaryManage/salaryChart';

import { isSuccess } from '@/utils/request';

const { TreeNode } = TreeSelect;

const SalaryItemsSelect = forwardRef(({
    organizationCode,
    itemType,
    extraType = 0,
    onChange,
    value,
    selectArr = [], // 跟isOwnTree搭配使用
    isOwnTree = false, // 数据来源是否自带
    ...selectProps
}) => {
    const [treeList, setTreeList] = useState([])
    useEffect(() => {
        const initFn = async () => {
            const request = await querySalaryItemsTree({
                organizationCode,
                itemType,
                extraType
            })
            if (isSuccess(request)) {
                setTreeList(request.data)
            }
        }
        if (!isOwnTree) {
            initFn()
        }

        return () => {
            setTreeList([])
        }
    }, [])

    useEffect(() => {
        if (isOwnTree && selectArr.length) {
            setTreeList(selectArr)
        }
    }, [isOwnTree, selectArr])

    const handleChange = (e, option) => {
        onChange(e, option);
    };

    return (
        <TreeSelect
            onChange={handleChange}
            placeholder="请选择薪资项"
            value={value}
            showArrow
            treeDefaultExpandAll
            {...selectProps}
        >
            {
                treeList?.map(({ name, id, children }) => (
                    <TreeNode title={name} value={id} key={id} selectable={!children} checkable={!children} >
                        {
                            children?.map(child => <TreeNode title={child.name} value={child.id} key={child.id} />)
                        }
                    </TreeNode>
                ))
            }
        </TreeSelect>
    )
})

export default SalaryItemsSelect
